#!/usr/bin/env python
import itk
import sys

import imageTools.ITKUtils.filter as filter
import imageTools.ITKUtils.io as io
import imageTools.ITKUtils.view as view
import imageTools.ITKUtils.itkmath as itkmath
from optparse import OptionParser

def getParser():
    try:
        parser = OptionParser()
        parser.add_option("-i", "--img", dest="filename", help="image to read and threshold")
        parser.add_option("-m", "--mask", dest="maskname", help="file to store mask")
        parser.add_option("-t", "--thresh", dest='threshold',nargs=2, default=(-150, 230), type='int')
        parser.add_option("-r", "--rescale",action='store_true', dest='rescale',default=False)
        return parser
    except Exception,  error:
        print "failed to generate parser",  error
        
def main():
    try:
        parser = getParser()
        
        (options, args) = parser.parse_args()
        
        iType = itk.Image[itk.F, 3]
        oType = itk.Image[itk.UC, 3]
        
        img = io.readImage(options.filename, iType=iType)
        if(options.rescale):
            img = filter.rescaleImage(img, [0, 1000])
        thresh = options.threshold[0], options.threshold[1]
        while(True):
            mask = filter.thresholdImage(img, thresh, (0, 1), iType=iType)
            img2 = itkmath.multiplyImages(img, mask)
            view.view3DImage([img, img2], title="Threshold=%d,%ds"%thresh)
            q = raw_input("Hit enter to accept current segmentation or type in a new theshold pair as low, high: ")
            if( not q):
                break
            else:
                try:
                    q = q.split(',')
                    thresh = int(q[0]), int(q[1])
                except:
                    print "invalid entry. Repeating with current threshold"
                    
        io.writeImage(mask, fname=options.maskname)
    except Exception,  error:
        print "failed in main()",  error
        
if __name__ == '__main__':
    main()
        
        
        
